import { Component, OnInit } from "@angular/core";
import { Subject, Subscription } from "rxjs";
import { Router, ActivatedRoute } from "@angular/router";
import { PostService } from '../post.service';

@Component({
  selector: "app-post-list",
  templateUrl: "./post-list.component.html",
  styleUrls: ["./post-list.component.scss"]
})
export class PostListComponent implements OnInit {
  public postList: Array<any> = [];
  public itemsPerPage = 10;
	public totalRecords = 11;
	public currentPage = 1;
	public offset = 0;
	public end = 0;

  private searchTextStream$: Subject<any> = new Subject<any>();

  constructor(
    private router: Router,
    private activeedRoute: ActivatedRoute,
    private postService: PostService
  ) {}

  ngOnInit(): void {
    // 从路由里面获取参数
    this.activeedRoute.params.subscribe(params => {
      console.log(params);
      this.currentPage = params.page;
      this.loadData();
    });
  }

  public loadData(): Subscription {
    this.offset = (this.currentPage - 1) * this.itemsPerPage;
		this.end = (this.currentPage) * this.itemsPerPage;
		return this.postService.getPostList().subscribe(
			res => {
				this.postList = res["items"].slice(this.offset, this.end > this.totalRecords ? this.totalRecords : this.end);
			},
			error => { console.log(error) },
			() => { }
		);
  }
}
